<?php
namespace app\admin\model;
use think\Loader;
use \think\Model;

class CategroySpecification extends Model
{
    protected $pk = 'id';
    protected $table = 'sdb_categroy_specification';

    /**
     * 添加分类规格
     * @param $data
     * @return array
     */
    public function addSpec($data)
    {
        //1、字段验证
        $validate = Loader::validate('CategroySpecification');
        if(!$validate->check($data)){
            return ['valid'=>0,'message'=>$validate->getError()];
        }else{
            $res = $this->where('categroy_id',$data['categroy_id'])->where('spec_staff',$data['spec_staff'])->count();
            if($res >= 1) return ['valid'=>2,'message'=>'同分类不能重复添加同级规格'];
            $recode = $this->where('categroy_id',$data['categroy_id'])->where('spec_name',$data['spec_name'])->count();
            if($recode >= 1) return ['valid'=>4,'message'=>'同分类不能重复添加同名规格'];
            if($data['spec_staff'] == 1){
                $re = $this->where('categroy_id',$data['categroy_id'])->where('spec_staff',0)->count();
                if(!$re) return ['valid'=>3,'message'=>'请先添加该分类的一级规格'];
            }
            $data['create_time'] = time();
            $result = $this->save($data);
            if(!$result){
                return ['valid'=>0,'message'=>'规格添加失败'];
            }
            return ['valid'=>1,'message'=>'规格添加成功'];
        }

    }
    /**
     * 编辑分类规格
     * @param $data
     * @return array
     */
    public function updateSpec($data)
    {
        $validate = Loader::validate('CategroySpecification');
        if(!$validate->check($data)){
            return ['valid'=>0,'message'=>$validate->getError()];
        }else{
            $res = $this->where('categroy_id',$data['categroy_id'])->where('spec_name',$data['spec_name'])->count();
            if($res >=1){
                return ['valid'=>2,'message'=>'同分类的一二级规格名称不能相同'];
            }
            $data['update_time'] = time();
            $result = $this->where('categroy_id',$data['categroy_id'])->where('spec_staff',$data['spec_staff'])->update($data);
            if(!$result){
                return ['valid'=>0,'message'=>'规格编辑失败'];
            }
            return ['valid'=>1,'message'=>'规格编辑成功'];
        }
    }

}